/*
 * @Author: gk 
 * @Date: 2018-04-14 12:36:45 
 * @Last Modified by: txy
 * @Last Modified time: 2019-10-27 15:45:29
 * 多选组下拉框列表
 */

layui.define(['zlConfig'], function (exports) {
    "use strict";
    var $ = layui.$
        , win = $(window)
        , zlConfig = layui.zlConfig
        , statusName = zlConfig.global.result.statusName
        , msgName = zlConfig.global.result.msgName
        , dataName = zlConfig.global.result.dataName
        , ERROR = zlConfig.global.result.errorState
        , OK = zlConfig.global.result.okState
        , obj = {}
        , CLASS = 'layui-form-select'
        , TITLE = 'layui-select-title'
        , HIDE = 'layui-hide'
        , DISABLED = 'layui-disabled'
        , OPERATIONBTN = 'selectMulti-cz'


    //组件重画消息处理
    layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.WM_DRAW, null, function (WParam) {
        if (WParam && $(WParam.elem).attr('class') && $(WParam.elem).attr('class').indexOf('select-multiple') >= 0) {
            obj.render($(WParam.elem), WParam.value);
        }
    });

    obj = {
        render: function ($elem, value, options) {
            if ($elem.attr('loaded')) {
                return;
            }
            var options = ($elem.attr('settings') ? eval('(' + $elem.attr('settings') + ')') : {})
                , dataurl = options.dataurl
                , datas = eval('('+options.sourcedata+')') || []
                , isMultiple = options.Multiple
                , chkboxType = eval('(' + options.chkboxType + ')')
                , maxtip = '最多能选择' + options.maxlength + '个'
                , defaultOptions = {
                    Multiple: false
                    , method: 'get'
                    , titlefield: 'name'
                    , valuefield: 'value'
                    , params: '{}'
                    , dataurl: ""
                    , value: ""
                    , placeholder: "请选择"
                    , edittype: (options.edittype == undefined ? "" : options.edittype)
                    , max: (options.maxlength == undefined ? "" : maxtip)
                    , issearch: 'off'
                    , showtool: true

                };
            var cmpName = $elem.attr('name');
            options = $.extend({}, defaultOptions, options);
            if (options.edittype == 'disabled') {
                options.placeholder = ' '
            }
            if (!$elem.attr('loaded')) {
                if ($elem.length != 1) {
                    layui.error("重复或不存在的组件名称[" + $elem.attr("name") + "]");
                    return;
                } else if ((dataurl == undefined || dataurl == "") && options.sourcedata.length==0) {
                    layui.error("请配置请求！");
                    return;
                }else if(dataurl == undefined && options.sourcedata == undefined){
                    layui.error('未找到数据或数据源链接！');
                    return;
                }
                var isSuccess = false;
                if(dataurl != undefined && dataurl != ""){
                    $.ajax({
                        type: options.method
                        , async: false
                        , url: dataurl
                        , data: eval('(' + options.params + ')')
                        , dataType: 'json'
                        , success: function (res) {
                            if (res['state'] == 'OK') {
                                datas = res['obj'];
                                isSuccess = true;
                                $elem.attr('loaded', 1);
                            } else {
                                throw Error(res['state']);
                                isSuccess = false;
                            }
                        }
                        , error: function (e, m) {
                            throw Error(m);
                            isSuccess = false;
                        }
                    });
                    if (!isSuccess && dataurl != undefined) { return; }
                }else{
                    $elem.attr('loaded', 1);
                }
                options.value = ((value == undefined || value == null || value == "") ? options.value : value)
                obj.init($elem, options, datas);
            }
        },
        init: function ($elem, options, datas) {
            var valus = [],
                items = [],
                toolhtml = [],
                searchhtml = [],
                cmpName = $elem.attr('name'),
                layVerify = $elem.attr('lay-verify'),
                checkClass = '',
                checked = 'checked';
            for (var i = 0; i < datas.length; i++) {
                if (options.maxlength === (i - 1)) {
                    return
                }
                if (options.value.indexOf(datas[i][options.valuefield]) >= 0) {
                    valus.push(
                        [
                            , '<a href="javascript:;">'
                            , '   <span>' + datas[i][options.titlefield] + '</span>'
                            , '   <i style="' + (options.edittype == "" ? "" : "display:none") + '"></i>'
                            , '</a>'
                        ].join('')
                    );
                    checkClass = 'layui-select layui-form-checkbox layui-form-checked';
                    checked = 'checked';
                } else {
                    checkClass = 'layui-select layui-form-checkbox';
                    checked = '';
                }
                items.push([
                    , '<dd lay-value="' + datas[i][options.valuefield] + '" class="selectMulti-dd">'
                    , '   <input type="checkbox" lay-filter="searchChecked" ' + checked + ' ' + options.edittype + ' title="' + datas[i][options.titlefield] + '" lay-skin="primary">'
                    , '   <div class="' + checkClass + '" lay-skin="primary">'
                    , '     <span>' + datas[i][options.titlefield] + '</span>'
                    , '     <i class="layui-icon"></i>'
                    , '   </div>'
                    , '</dd>'
                ].join(''));
            }

            if(options.showtool){
            toolhtml.push([
                , '<dd lay-value="" class="selectMulti-tips" style="background-color: #FFF!important;">'
                , '   <div class="selectMulti-cz-group" show="null">'
                , '   	<div class="selectMulti-cz" handle="selectAll" title="全选">'
                , '    	  <i class="zlui-icon zlui-icon-check-all"></i>'
                , '       <span>全选</span>'
                , '     </div>'
                , '   	<div class="selectMulti-cz" handle="removeAll" title="清空">'
                , '    	  <i class="zlui-icon zlui-icon-clean"></i>'
                , '       <span>清空</span>'
                , '     </div>'
                , '   	<div class="selectMulti-cz" handle="reverseAll" title="反选">'
                , '    	  <i class="zlui-icon zlui-icon-check-invert"></i>'
                , '       <span>反选</span>'
                , '     </div>'
                , '   </div>'
                , '</dd>'
                ].join(''));
            }
            if (options.issearch == "on") {
                searchhtml.push([
                    , '<dd lay-value="" class="selectMulti-search" style="background-color: #FFF!important;cursor:text">'
                    , '    <div class="layui-form" style="position: relative;">'
                    , '        <input type="text"  placeholder="请输入关键词" id="selectmultikey" class="layui-input" style="margin-left:0px;border-color:#e6e6e6">'
                    , '        <span class="layui-btn layui-btn-sm layui-btn-normal" id="selectmulti-search-btn" style="position: absolute;top: 0;right: 0px;height:38px;line-height:38px">'
                    , '            <i class="layui-icon">&#xe615;</i>'
                    , '        </span>'
                    , '    <div>'
                    , '</dd>'
                ].join(''));
            }
            toolhtml.push(searchhtml.join(''));
            var html = [
                '    <div class="layui-select-title">'
                //, '    <input type="text" class="layui-input" id="' + cmpName + 'show" placeholder = "' + options.placeholder + '">'
                , '    <input type="hidden" class="layui-input" ' + (layVerify ? 'lay-verify=' + layVerify : '') + ' name="' + cmpName + '">'
                , '    <div class="layui-input selectMulti">'
                , '       <a class="tipname">' + (!options.value ? options.placeholder : "") + ((options.max != "" && !options.value) ? options.max : "") + '</a>'
                , '       <i class="layui-edge"></i>'
                , valus.join('')
                , '    </div>'
                , '    <dl class="layui-anim layui-anim-upbit">'
                , toolhtml.join('')
                , items.join('')
                , '    </dl>'
                , '</div>'
            ];

            $elem.append(html.join(''));

            if (options.edittype == 'disabled') {
                $elem.find('.' + TITLE).find(".selectMulti").css({
                    'background-color': 'rgba(247, 244, 244, 0.63)',
                    'color': 'rgba(8, 8, 8, 0.63) !important',
                    'cursor': 'not-allowed'
                })
                return;
            }

            var $title = $elem.find('.' + TITLE),
                $dl = $elem.find('dl'),
                $dds = $dl.children('dd.selectMulti-dd'),
                $input = $elem.find('input[type="hidden"]'),
                $selectMulti = $title.find(".selectMulti"),
                //展开下拉
                showDown = function ($elem) {
                    var top = $elem.offset().top + $elem.outerHeight() + 5 - win.scrollTop(),
                        dlHeight = $dl.outerHeight();
                    $("." + CLASS).removeClass(CLASS + 'ed');
                    $elem.addClass(CLASS + 'ed');
                    $dds.removeClass(HIDE);
                    //上下定位识别
                    if (top + dlHeight > win.height() && top >= dlHeight) {
                        $elem.addClass(CLASS + 'up');
                    }
                    //宽度
                    $dl.width($elem.parent().width());
                    $elem.bind("mousedown", onBodyDown);
                    $dds.each(function () {
                        $(this).show();
                    });
                },
                //隐藏下拉
                hideDown = function (choose) {
                    $elem.removeClass(CLASS + 'ed ' + CLASS + 'up');
                    $elem.bind("mousedown", onBodyDown);
                    if (options.issearch == "on") {
                        $elem.find('#selectmultikey').val("");
                    }
                },
                onBodyDown = function (event) {
                    var maxStr = '';
                    if ($input.val() == "") {
                        if (options.max != "")
                            maxStr = '，' + options.max;
                        $title.find('.tipname').show().text(options.placeholder + maxStr);
                    }
                    if ($(event.target).parents(".layui-select-title").html() == null) {
                        hideDown();
                    }
                },
                setValue = function (value) {
                    $input.val(value);
                };
            //初始化值
            setValue(options.value ? options.value : '');
            //选择
            $dds.on('click', function (e) {
                var othis = $(this),
                    value = othis.attr('lay-value'),
                    valueStr = ($input.val() && $input.val().split(',')) || [];
                if (othis.hasClass(DISABLED)) return false;
                if (othis.find("input[type='checkbox']").is(':checked')) {
                    if (valueStr.length >= options.maxlength) {
                        othis.find('div').removeClass('layui-form-checked');
                        $input.val(valueStr);
                        $input.parents('.select-multiple').addClass('layui-form-danger');
                        return false
                    }
                    if (valueStr.length === 0 || valueStr.indexOf(value) === -1) {
                        $selectMulti.find(".tipname").hide();
                        $selectMulti.html($selectMulti.html() + '<a href="javascript:;"><span>' + othis.find('span').text() + '</span><i></i></a>');
                        valueStr.push(value);
                    }
                } else {
                    $selectMulti.find('a').each(function () {
                        if ($(this).find('span').text() == othis.find('span').text()) {
                            $(this).remove();
                            valueStr.removeElem(value);
                        }
                    })
                }
                $input.val(valueStr);
                setTimeout(function () { $input.parents('.select-multiple').removeClass('layui-form-danger') }, 3000);
                obj.tip($elem, options);
                e.stopPropagation();
                layui.event.call(this, 'zlSelectMultiple', 'div(' + cmpName + ')', {
                  elem: $elem[0]
                  , value: valueStr
                  , othis: $elem[0]
                });
            });
            //点击出现下拉框
            $title.on('click', function (e) {
                if (!$elem.hasClass(CLASS + 'ed')) {
                    showDown($elem);
                } else {
                    hideDown();
                    obj.tip($elem, options);
                }
                e.stopPropagation();
            });
            //多选删除并维护值字符串
            $title.delegate('.selectMulti a i', "click", function (e) {
                var valueStr = ($input.val() && $input.val().split(',')) || [];
                var _this = $(this);
                e.stopPropagation();
                $title.find('dd').each(function () {
                    if ($(this).find('span').text() == _this.siblings('span').text()) {
                        var othis = $(this);
                        $(this).find('input').removeAttr('checked');
                        $(this).find('.layui-form-checkbox').removeClass('layui-form-checked');
                        valueStr.removeElem($(this).attr('lay-value'));
                        $input.val(valueStr);
                    }
                })
                $(this).parent('a').remove();
                obj.tip($elem, options);
                layui.event.call(this, 'zlSelectMultiple', 'div(' + cmpName + ')', {
                    elem: $elem[0]
                    , value: valueStr
                    , othis: $elem[0]
                  });
            })
            $("body").bind("mousedown", onBodyDown);

            //操作栏点击事件
            $elem.find('.' + OPERATIONBTN).on('click', function (e) {
                var _this = $(this),
                    handle = _this.attr('handle');
                obj.toolOperation($elem, options, handle);
                e.stopPropagation();
            });

            //搜索框
            $elem.find('#selectmultikey').off().on('click', function (e) {
                e.stopPropagation();
            });
            $elem.find("#selectmultikey").bind('keydown', function (e) {//给输入框绑定按键事件
                if (e.keyCode == "13") {//判断如果按下的是回车键则执行下面的代码
                    var insertVal = $(this).val();//手动输入的字符串；
                    $dds.each(function () {
                        var paraStr = $(this).find('span').text();
                        if (paraStr.indexOf(insertVal) < 0) {//不包含
                            $(this).hide();
                        } else {//包含
                            $(this).show();
                        }
                    });
                    e.preventDefault();
                }
                e.stopPropagation();
            });
            //搜索框
            $elem.find('#selectmulti-search-btn').on('click', function (e) {
                var insertVal = $('#selectmultikey').val();//手动输入的字符串；
                $dds.each(function () {
                    var paraStr = $(this).find('span').text();
                    if (paraStr.indexOf(insertVal) < 0) {//不包含
                        $(this).hide();
                    } else {//包含
                        $(this).show();
                    }
                });
                e.stopPropagation();
            });
        },
        // 工具栏操作
        toolOperation: function ($elem, options, handle) {
            if (options.edittype == 'disabled') return false;
            var $dl = $elem.find('dl'),
                $dds = $dl.children('dd.selectMulti-dd'),
                $input = $elem.find('input[type="hidden"]'),
                $selectMulti = $elem.find(".selectMulti"),
                selectedVal = [],//临时数组
                valueStr = ($input.val() && $input.val().split(',')) || [];
            $dds.each(function () {
                var _this = $(this),
                    value = _this.attr('lay-value');
                switch (handle) {
                    // 全选
                    case "selectAll":
                        $selectMulti.find(".tipname").hide();
                        if (valueStr.length === 0 || valueStr.indexOf(value) === -1) {
                            if (valueStr.length >= options.maxlength) {
                                _this.find('div').removeClass('layui-form-checked');
                                $input.val(valueStr);
                                $input.parents('.select-multiple').addClass('layui-form-danger');
                                return false
                            }
                            _this.find('input').prop('checked', true);
                            _this.find('div').addClass('layui-form-checked');
                            $selectMulti.html($selectMulti.html() + '<a href="javascript:;"><span>' + _this.find('span').text() + '</span><i></i></a>');
                            valueStr.push(value);
                        }
                        break;
                    // 清空
                    case "removeAll":
                        if (valueStr.length == 0) return false;
                        _this.find('input').prop('checked', false);
                        _this.find('div').removeClass('layui-form-checked');
                        valueStr.removeElem(_this.attr('lay-value'));
                        $selectMulti.find('a').eq(0).nextAll('a').remove();
                        break;
                    // 反选
                    case "reverseAll":
                        if (_this.find('input').prop('checked')) {
                            _this.find('input').prop('checked', false);
                            _this.find('div').removeClass('layui-form-checked');
                            valueStr.removeElem(_this.attr('lay-value'));
                            $selectMulti.find('a').each(function () {
                                if ($(this).find('span').text() == _this.find('span').text()) {
                                    $(this).remove();
                                }
                            })
                        } else {
                            $selectMulti.find(".tipname").hide();
                            if (selectedVal.length >= options.maxlength) {
                                _this.find('div').removeClass('layui-form-checked');
                                $input.val(valueStr);
                                $input.parents('.select-multiple').addClass('layui-form-danger');
                                return true;
                            } else {
                                _this.find('input').prop('checked', true);
                                _this.find('div').addClass('layui-form-checked');
                                selectedVal.push(value);
                            }
                            $selectMulti.html($selectMulti.html() + '<a href="javascript:;"><span>' + _this.find('span').text() + '</span><i></i></a>');
                            valueStr.push(value);
                        }
                        break;
                }

            })
            $input.val(valueStr);
            obj.tip($elem, options);
            setTimeout(function () { $input.parents('.select-multiple').removeClass('layui-form-danger') }, 3000);
        },
        //placeholder提示
        tip: function ($elem, options) {
            var $title = $elem.find('.' + TITLE),
                $input = $elem.find('input[type="hidden"]'),
                maxStr = '';
            if ($input.val() == "") {
                if (options.max != "")
                    maxStr = '，' + options.max;
                $title.find('.tipname').show().text(options.placeholder + maxStr);
            }
        }
        , on: function (events, callback) {
            return layui.onevent.call(this, 'zlSelectMultiple', events, callback);
        }
    }
    exports('zlSelectMultiple', obj);
});